const axios = require('axios')
const cheerio = require('cheerio')
const FormData = require('form-data')

function puppeteerRequestIcon (url) {
  return new Promise((resolve) => {
    axios.get(url, {
      xhrFields: {
        withCredentials: true
      },
      headers: {
        Referer: url,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
      }
    }).then(response => {
      const $ = cheerio.load(response.data)
      const icon = $("link[rel~='icon']").attr('href')
      if (!icon) {
        return resolve(null)
      }
      const regex = /\/\/[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+([a-zA-Z0-9_-]*)?/
      if (regex.test(icon)) {
        resolve(icon)
      } else {
        const regex = /^(https?:\/\/)?([\w.-]+)(:\d+)?/i
        const matches = url.match(regex)
        const protocol = matches[1] ? matches[1].slice(0, -3) : 'http'
        const domain = matches[2]
        const port = matches[3] ? ':' + matches[3].slice(1) : ''
        resolve(protocol + '://' + domain + port + '/' + icon)
      }
    }).catch(() => {
      resolve(null)
    })
  })
}

async function uploadIconStream (url) {
  try {
    const iconurl = await puppeteerRequestIcon(url)
    if (iconurl) {
      const response = await axios({
        url: iconurl,
        method: 'GET',
        responseType: 'stream'
      })
      if (response.status === 200) {
        const formData = new FormData()
        formData.append('file', response.data)
        const { data } = await axios({
          url: 'https://image.zdxblog.cn/upload/uploadFile',
          data: formData,
          method: 'post',
          headers: { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary}` }
        })
        if (data.code === '0') {
          return data.data
        }
      }
      return iconurl
    }
    return null
  } catch (error) {
    return null
  }
}

module.exports = uploadIconStream
